package com.chx.rpc05;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private static boolean running=true;

    public static void main(String[] args)throws Exception {
        ServerSocket s = new ServerSocket(8080);
        while(running){
            Socket socket = s.accept();
            process(socket);
            socket.close();
        }
        s.close();
    }

    private static void process(Socket socket)throws Exception {
        InputStream is = socket.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        String className=ois.readUTF();
        String methodName=ois.readUTF();
        Class<?> clazz = Class.forName(className);
        Class[] classes=(Class[])ois.readObject();
        Object[] objects = (Object[]) ois.readObject();
        Method method = clazz.getMethod(methodName, classes);
        Object o = method.invoke(clazz.newInstance(),objects);

        OutputStream os=socket.getOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(os);
        oos.writeObject(o);
        oos.flush();

        ois.close();
        oos.close();
    }
}
